using LuaInterface;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.EventSystems;
using TMPro;
using System.Collections.Generic;

namespace Framework.UGUI
{
    public class TMPDropdownWrap : MonoBehaviour
    {
        public static TMPDropdownWrap Get(GameObject go)
        {
            TMP_Dropdown dropdown = go.GetComponent<TMP_Dropdown>();
            if (dropdown != null)
            {
                return go.OnceAddComponent<TMPDropdownWrap>();
            }
            return null;
        }

        public static TMPDropdownWrap GetWithPath(GameObject go, string path)
        {
            var dropDownTransform = go.transform.Find(path);
            if (dropDownTransform != null)
            {
                return Get(dropDownTransform.gameObject);
            }
            return null;
        }

        private TMP_Dropdown _dropDown;
        public TMP_Dropdown dropDown
        {
            get
            {
                if (_dropDown == null)
                {
                    _dropDown = gameObject.GetComponent<TMP_Dropdown>();
                }
                return _dropDown;
            }
        }

        public void AddOptions(string[] options)
        {
            if (options == null || options.Length == 0)
            {
                Logger.LogWarning("TMPDropdownWrap.AddOptions, options is null or empty!");
                return;
            }
            dropDown.AddOptions(new List<string>(options));
        }

        public void ClearOptions()
        {
            dropDown.ClearOptions();
        }

        public void SetValue(int value)
        {
            dropDown.value = value;
        }

        public int GetValue()
        {
            return dropDown.value;
        }

        private GeneralCallBack _onValueChangedCallback;

        public void AddOnValueChanged(LuaFunction onValueChanged, LuaTable onValueChangedTarget)
        {
            GeneralCallBack.GetOrReUse(ref _onValueChangedCallback, onValueChanged, onValueChangedTarget);
            dropDown.onValueChanged.RemoveListener(OnValueChanged);
            dropDown.onValueChanged.AddListener(OnValueChanged);
        }

        public void RemoveOnValueChanged()
        {
            ClearValueChangedCallback();
            dropDown.onValueChanged.RemoveListener(OnValueChanged);
        }

        private void ClearValueChangedCallback()
        {
            GeneralCallBack.RecycleInst(ref _onValueChangedCallback);
        }

        private void OnValueChanged(int index)
        {
            if (_onValueChangedCallback != null)
            {
                GeneralCallBack.Invoke(ref _onValueChangedCallback, index);
            }
        }

        void OnDestroy()
        {
            if (_onValueChangedCallback != null)
            {
                UIEventDebugger.LogUIEventError("TMPDropdownWrap.onValueChanged", gameObject);
            }
            ClearValueChangedCallback();
        }
    }
}